<template>
  <el-card class="app-container content_box" shadow="always">
    <div>
      <!-- <div class="header_title_box">
        <h2>采购付款管理</h2>
      </div> -->
      <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
      <div class="select_flex">
        <div />
        <div>
          <el-button size="small" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button size="small" icon="el-icon-refresh" @click="handleRefreshSelf">刷新</el-button>
          <el-button size="small" @click="isActive=!isActive">{{ isActive?'展开':'收起' }}</el-button>
        </div>
      </div>
      <div v-loading="loading" class="mt25">
        <el-table ref="multipleTable" :data="data" tooltip-effect="dark" style="width: 100%" :max-height="screenHeigh" border fit @selection-change="handleSelectMulti">
          <!-- <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" /> -->
          <el-table-column align="center" label="操作" width="150" fixed>
            <template slot-scope="sales">
              <span v-if="sales.row.audit_status !== 1" v-action="'purchasePayment@changeAuditStatus'" class="pointer green_style" @click="
                  dataItem = sales.row;
                  formVisibleA = true;
                  orderId = sales.row.id;
                ">付款单审核</span>
              <span v-if="
                  sales.row.audit_status === 1 && sales.row.pay_status === 0
                " v-action="'purchasePayment@pay'" class="pointer blue" @click="
                  formVisible = true;
                  orderId = sales.row.id;
                ">录入实际付款</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="付款单号" prop="payment_no" width="170px" />
          <el-table-column align="center" label="付款单来源" prop="source" width="110px" />
          <el-table-column align="center" label="出运单号" prop="trans_code" width="210px">
            <template slot-scope="scope">
              {{ scope.row.trans_code ? scope.row.trans_code : "-" }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="合同编码" prop="contract_code" width="170px" />
          <el-table-column align="center" label="所属供应商" prop="supply_name" width="160" show-overflow-tooltip />
          <el-table-column align="center" label="应付金额" prop="order_amount" />
          <el-table-column align="center" label="审核状态" prop="audit_status">
            <template slot-scope="scope">
              {{
                scope.row.audit_status === 0
                  ? "待审核"
                  : scope.row.audit_status === 1
                    ? "审核通过"
                    : "审核驳回"
              }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="审核原因" prop="audit_status" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.audit_notes ? scope.row.audit_notes : "-" }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="付款状态" prop="pay_status">
            <template slot-scope="scope">
              {{ scope.row.pay_status === 1 ? "已付款" : "未付款" }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="预计付款时间" prop="estimated_pay_time" width="110px">
            <template slot-scope="scope">
              {{
                scope.row.estimated_pay_time
                  ? scope.row.estimated_pay_time
                  : "-"
              }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="付款抬头" prop="pay_title" width="130px" show-overflow-tooltip />
          <el-table-column align="center" label="实际付款金额" prop="pay_amount" width="110px" />
          <el-table-column align="center" label="实际付款时间" prop="pay_time" width="170px">
            <template slot-scope="scope">
              {{ scope.row.pay_time | formatDate("{y}-{m}-{d}") }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作人" prop="creator" width="130">
            <template slot-scope="scope">
              {{ scope.row.creator ? scope.row.creator : "-" }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="created_at" label="操作时间" width="170px" />
        </el-table>
        <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <!-------- 回到顶部 ------------>
      <el-backtop :visibility-height="60">
        <i class="el-icon-caret-top" />
      </el-backtop>
      <!-- 审核 -->
      <el-dialog :center="true" title="审核" :visible.sync="formVisibleA" width="65%" @close="handleCancelA">
        <div>
          <el-form :model="dataItem" inline label-width="150px">
            <el-row :gutter="20">
              <el-col :span="7">
                <el-form-item label="付款单号：">
                  {{ dataItem.payment_no }}
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="付款单来源：">
                  {{ dataItem.source }}
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="供应商：">
                  {{ dataItem.supply_name }}
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="合同编号：">
                  {{ dataItem.contract_code }}
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="应付金额：">
                  {{ dataItem.order_amount }}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div style="margin-top:30px">
          <div class="header_title_box">
            <h2 style="margin-right:50px">
              审核意见
            </h2>
          </div>
          <div>
            <el-form ref="ruleForm" :model="formExamine" :rules="rules" label-width="140px">
              <el-form-item prop="audit_status">
                <el-radio-group v-model="formExamine.audit_status">
                  <el-radio label="1">通过</el-radio>
                  <el-radio label="2">驳回</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item :label="
                  `${
                    formExamine.audit_status === '1' ? '通过说明' : '驳回原因'
                  }`
                ">
                <el-input v-model="formExamine.audit_notes" type="textarea" autosize placeholder="请输入最多200字符" maxlength="200" show-word-limit />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div style="text-align: center; margin-top:50px">
          <el-button type="primary" :loading="isbtn" @click="submitFormA('ruleForm')">确认审核</el-button>
          <el-button @click="handleCancelA">取消审核</el-button>
        </div>
      </el-dialog>
      <!-- 实际付款金额 -->
      <el-dialog :center="true" title="录入实际付款金额" :visible.sync="formVisible" width="600px" @close="handleCancel">
        <div>
          <el-form :ref="formName" :model="formFieldsData" :rules="rules" label-width="140px">
            <el-form-item prop="pay_title" label="付款抬头">
              <el-select v-model="formFieldsData.pay_title" placeholder="请选择" filterable clearable style="width:300px">
                <el-option v-for="item in supplyList" :key="item.id" :value="item.name" :label="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item prop="pay_time" label="实际付款时间">
              <el-date-picker v-model="formFieldsData.pay_time" type="date" value-format="timestamp" placeholder="选择日期" style="width:300px" />
            </el-form-item>
            <el-form-item label="实际付款金额" prop="pay_amount">
              <el-input v-model="formFieldsData.pay_amount" placeholder="请输入实际付款金额" style="width:300px" />
            </el-form-item>
          </el-form>
        </div>
        <div style="text-align: center; margin-top:50px">
          <el-button type="primary" :loading="isbtn" @click="submitFormPay">确认付款</el-button>
          <el-button @click="handleCancel">取消付款</el-button>
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'FinancePurchase',
  directives: {
    action
  },
  mixins: [formOperate, cacheList],
  data() {
    return {
      otherHeight: 400,
      queryParam: {
        payment_no: '',
        supply_name: '',
        trans_code: '',
        pay_status: '',
        start_at: '',
        end_at: ''
      },
      formItems: [
        {
          label: '付款单号',
          key: 'payment_no',
          type: 'input',
          placeholder: '请输入付款单号'
        },
        {
          label: '供应商',
          key: 'supply_name',
          type: 'input',
          placeholder: '请输入供应商'
        },
        {
          label: '出运单号',
          key: 'trans_code',
          type: 'input',
          placeholder: '请输入出运单号'
        },
        {
          label: '付款状态',
          key: 'pay_status',
          type: 'select',
          placeholder: '请选择付款状态',
          options: [
            {
              value: 0,
              label: '待付款'
            },
            {
              value: 1,
              label: '已付款'
            }
          ]
        },
        {
          label: '操作时间',
          key: 'date',
          type: '',
          //   valueFormat: 'timestamp',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      componentName: 'FinancePurchase',
      formVisibleA: false,
      dataItem: {},
      formExamine: {
        audit_status: '1',
        audit_notes: ''
      },
      isbtn: false,
      orderId: '',
      url: '/purchase-payment',

      date: [],
      loading: false,
      formVisible: false,
      formName: 'payment',
      formLabelWidth: '150px',
      formFieldsData: {
        pay_title: '',
        pay_time: '',
        payaway_amount_real: ''
      },
      supplyList: [],
      rules: {
        audit_status: [
          {
            required: true,
            message: '请选择审核状态',
            trigger: 'blur'
          }
        ],
        pay_title: [
          { required: true, message: '请输入付款抬头', trigger: 'blur' }
        ],
        pay_time: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        pay_amount: [
          { required: true, message: '请输入金额', trigger: 'change' },
          {
            pattern: /\d+(\.[0-9]{1,4}){0,1}$/,
            message: '只能输入数字,最多四位小数',
            trigger: 'change'
          }
        ]
      }
    }
  },
  created() {
    const vm = this
    vm.getSupplyList()
  },
  methods: {
    beforeSearch() {
      const vm = this
      vm.queryParam.start_at_pay = ''
      vm.queryParam.end_at_pay = ''
      vm.queryParam.start_at = ''
      vm.queryParam.end_at = ''
      vm.queryParam.start_at_creat = ''
      vm.queryParam.end_at_creat = ''
      //   if (vm.payDate.length === 2) {
      //     const [start_at_pay, end_at_pay] = vm.payDate
      //     // vm.queryParam.start_at_pay = parseInt(start_at_pay / 1000)
      //     // vm.queryParam.end_at_pay = parseInt(end_at_pay / 1000)
      //     vm.queryParam.start_at_pay = vm.queryParam.payDate[0]
      //     vm.queryParam.end_at_pay = vm.queryParam.payDate[1]
      //   }
      if (vm.queryParam.date && vm.queryParam.date.length > 0) {
        vm.queryParam.start_at = vm.queryParam.date[0]
        vm.queryParam.end_at = vm.queryParam.date[1]
      }
      // 生成日期转化
      if (vm.queryParam.dateCreat && vm.queryParam.dateCreat.length > 0) {
        // const [start_at_creat, end_at_creat] = vm.queryParam.dateCreat
        // vm.queryParam.start_at_creat = parseInt(start_at_creat / 1000)
        // vm.queryParam.end_at_creat = parseInt(end_at_creat / 1000)
        vm.queryParam.start_at_creat = vm.queryParam.dateCreat[0]
        vm.queryParam.end_at_creat = vm.queryParam.dateCreat[1]
      }
      if (vm.queryParam.category_ids && vm.queryParam.category_ids.length > 0) {
        // vm.queryParam.category_id = vm.queryParam.category_ids.pop()
        const arr = vm.queryParam.category_ids
        vm.queryParam.category_id = arr[arr.length - 1]
      } else {
        vm.queryParam.category_id = ''
      }
    },
    // 关闭
    handleCancel() {
      this.formVisible = false
      this.isInfo = false
      // 防止提交关闭的时候 导致数据清空 所以延迟 300ms 清空数据
      this.formFieldsData.pay_title = ''
      this.formFieldsData.pay_time = ''
      this.formFieldsData.payaway_amount_real = ''
      setTimeout(() => {
        this.$refs[this.formName].clearValidate()
      }, 300)
      if (this.afterCancel !== undefined) {
        this.afterCancel()
      }
    },
    getSupplyList() {
      const vm = this
      const params = {
        page: 1,
        limit: 1000,
        audit_status: 2,
        cooperation_status: 1
      }
      vm.$http.get('/supply', { params }).then(res => {
        vm.supplyList = res.data
      })
    },
    handleRefreshSelf() {
      const vm = this
      vm.handleRefresh(true)
      vm.date = []
    },
    // 修改时间处理函数
    changeDateHandler(date) {
      let start_at = ''
      let end_at = ''
      if (date?.length === 2) {
        [start_at, end_at] = date
      }
      this.queryParam.start_at = start_at
      this.queryParam.end_at = end_at
    },
    checkSelectable(row, index) {
      return row.audit_status !== 1
    },
    // 审核
    handleCancelA() {
      this.formVisibleA = false
    },
    // 付款
    submitFormPay() {
      this.$refs[this.formName].validate(valid => {
        if (valid) {
          this.isbtn = true
          const data = this.formFieldsData
          data.id = this.orderId
          this.$http
            .post(`/purchase-payment/pay`, data)
            .then(res => {
              if (res.code === 10000) {
                this.$message.success('录入成功')
                this.handleRefresh()
                this.handleCancel()
                this.resetFormFields()
              }
              this.isbtn = false
            })
            .catch(() => {
              this.isbtn = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 审核
    submitFormA(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.isbtn = true
          const data = this.formExamine
          data.id = this.orderId
          data.status = Number(data.status)
          this.$http
            .post(`/purchase-payment/change-audit-status`, data)
            .then(res => {
              if (res.code === 10000) {
                this.$message.success('审核成功')
                this.handleRefresh()
                this.handleCancelA()
              }
              this.isbtn = false
            })
            .catch(() => {
              this.isbtn = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content_box .wfull {
  width: 100%;
}
</style>
